<?php
include("config.php");
include("session.php");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$error = null;
# print_r($_SERVER);
if(  $_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("REQUEST_METHOD is not POST!");
}
    if(!validate(1, "record_time.php", $db, "maintime.php"))
        exit();

    $startdate = mysqli_real_escape_string($db,$_POST['startdate']);
    $stopdate = mysqli_real_escape_string($db,$_POST['stopdate']);
    $starttime = $_POST['starttime'];
    $stoptime = $_POST['stoptime'];
    $startdatetime = mysqli_real_escape_string($db,$startdate." ".$starttime.":00");
    $stopdatetime = mysqli_real_escape_string($db,$stopdate." ".$stoptime.":00");
    # Cases covered in Order:
    # 1. Intended Start-Time is within another time-record
    # 2. Intended End-Time is within another time-record
    # 3. Another record is enveloped within intended start and stop time
    $sql = "SELECT * FROM time WHERE (start <= ? and stop > ?) or (start < ? and stop >= ?) or (start >= ? and stop <= ?)";
    if(!$result = get_db_result($db,$sql, "ssssss", $startdatetime,$startdatetime,$stopdatetime,$stopdatetime,$startdatetime,$stopdatetime))
        die(mysqli_error($db));
    $count = mysqli_num_rows($result);

    if($count > 0){
        $_SESSION['msgtype'] = "error";
        $_SESSION['msg'] = RLang("err_times_overlap");
        header("Location: maintime.php");
        exit();
    }

    $hrs = get_hour_diff_from_sql_datetime($startdatetime, $stopdatetime);
    if(!$hrs){
        $_SESSION['msgtype'] = "error";
        $_SESSION['msg'] = RLang("err_start_after_stop");
        header("Location: maintime.php");
        exit();
    }

    $userid = mysqli_real_escape_string($db, $_SESSION['userid']);
    $text = mysqli_real_escape_string($db, $_POST['text']);
    $projectID = mysqli_real_escape_string($db, $_POST['project']);
    $sql = "INSERT INTO time(id, start, stop, project_id, user_id, hrs, text, billdate) values(null, ?, ?, ?, ?, ?, ?, null)";
    
    if(!$result = get_db_result($db,$sql, "ssiids", $startdatetime, $stopdatetime, $projectID, $userid, $hrs, $text)){
        echo($sql." ");
        die(mysqli_error($db));
    }
    $sql = "UPDATE user set last_project = ? where id = ?";
    if(!$result = get_db_result($db,$sql, "ii", $projectID, $userid)){
        echo($sql." ");
        die(mysqli_error($db));
    }
    $_SESSION['lastProject'] = $projectID;
    $_SESSION['lastCustomer'] = $_POST['customer'];
    $_SESSION['msgtype'] = "msg";
    $_SESSION['msg'] = sprintf(RLang("msg_save_success"), RLang("time"));
    header("Location: maintime.php");
    exit();
?>